package com.franklin.java.service.database;

import com.franklin.java.utils.ThreadUtils;
import com.franklin.java.utils.VirtualFileUtils;
import com.franklin.plugins.common.thread.MyCountDownLatch;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author Franklin
 * @since 2021/9/23 15:33
 */
public abstract class AbstractJdbcConsole implements MyJdbcConsole{

    protected Project project;

    /**
     * 待执行的SQL
     */
    protected final String sql;

    public AbstractJdbcConsole(Project project, String sql) {
        this.project = project;
        this.sql = sql;
    }

    protected VirtualFile getSqlFile(){
        return getSqlFile("mybatis");
    }

    protected VirtualFile getSqlFile(String dataSourceName){
        LocalFileSystem localFileSystem = LocalFileSystem.getInstance();

        String projectBasePath = project.getBasePath();
        String path = projectBasePath + "/.idea/mybatis-sql";
        String sqlFileName = dataSourceName + ".sql";
        String sqlFilePath = path + "/" + sqlFileName;
        VirtualFile mybatisFile = localFileSystem.refreshAndFindFileByPath(sqlFilePath);
        if (Objects.nonNull(mybatisFile)){
            return mybatisFile;
        }

        try {
            File file = new File(sqlFilePath);
            FileUtils.forceMkdirParent(file);
            FileUtils.writeStringToFile(file,"", StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getSqlFile(dataSourceName);
    }
}
